package com.atstudy.jdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.stream.Stream;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/1/10 13:51
 * @copyright: 博为峰
 */
public class JdbcDemo02 {
    public static void main(String[] args) throws SQLException {
        Connection connection = DBUtils.getConn();
        Student student = new Student("蛇年", "蛇", "29期", 2025, 2025, 1);
        query(connection);
        insert(connection, student);
        connection.close();
    }

    private static void insert(Connection connection, Student student) {
        try (PreparedStatement preparedStatement = connection.prepareStatement("insert into stu(name,sex,cla_name,age,score,cla_id) values (?,?,?,?,?,?)");
        ) {
            preparedStatement.setString(1, student.getName());
            preparedStatement.setString(2, student.getSex());
            preparedStatement.setString(3, student.getClaName());
            preparedStatement.setInt(4, student.getAge());
            preparedStatement.setInt(5, student.getScore());
            preparedStatement.setInt(6, student.getClaId());
            int i = preparedStatement.executeUpdate();
            System.out.println("i = " + i);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    private static void query(Connection connection) {
        ArrayList<Student> list = new ArrayList<Student>();
        try (PreparedStatement statement = connection.prepareStatement("select * from stu");
             ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                Student student = new Student();
                student.setId(resultSet.getInt("id"));
                student.setName(resultSet.getString("name"));
                student.setSex(resultSet.getString("sex"));
                student.setClaName(resultSet.getString("cla_name"));
                student.setAge(resultSet.getInt("age"));
                student.setScore(resultSet.getInt("score"));
                student.setCreateTime(resultSet.getDate("create_time"));
                student.setUpdateTime(resultSet.getDate("update_time"));
                student.setClaId(resultSet.getInt("cla_id"));
                list.add(student);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        Stream<Student> stream = list.stream();
        stream.forEach(System.out::println);
    }
}
